#include "qgis_hello_world.h"

#include <QFileDialog>
#include <QFileInfo>
#include <QToolBar>
#include <QProcess>

#include <qgsvectorlayer.h>
#include <qgsdataprovider.h>
#include <qgslayertree.h>
#include <qgslayertreeview.h>
#include <qgslayertreemodel.h>

#include <qgsgui.h>
#include <qgsprintlayout.h>
#include <qgslayoutitemmap.h>
#include <qgslayoutitempicture.h>
#include <qgslayoutitemlabel.h>
#include <qgslayoutitemnodeitem.h>
#include <qgslayoutmanager.h>
#include <qgslayoutitemguiregistry.h>
#include <qgslayoutexporter.h>
#include <qgslayoutpagecollection.h>
#include <qgslayoutdesignerinterface.h>


QGISEXTERN QgisPlugin* classFactory(QgisInterface* qgis_if)
{
   std::cout << "::classFactory" << std::endl;
   return new HelloWorldPlugin(qgis_if);
}


QGISEXTERN const QString* name() {
   return &s_name;
}

QGISEXTERN const QString* description() {
   return &s_description;
}

QGISEXTERN const QString* category() {
   return &s_category;
}

QGISEXTERN int type() {
   return s_type;
}

QGISEXTERN const QString* version() {
   return &s_version;
}

QGISEXTERN const QString* icon() {
   return &s_icon;
}

QGISEXTERN void unload(QgisPlugin* plugin) {
   std::cout << "::unload" << std::endl;
   delete plugin;
}

HelloWorldPlugin::HelloWorldPlugin(QgisInterface* iface) : QgisPlugin(s_name, s_description, s_category, s_version, s_type), m_qgis_if(iface) {
}


void HelloWorldPlugin::unload() {
   // TODO - need to remove the actions from the menu again.
}

void HelloWorldPlugin::initGui() {
   std::cout << "HelloWorldPlugin::initGui" << std::endl;

    auto mytoolbar = m_qgis_if->pluginToolBar();
    m_menu_action = mytoolbar->addAction(QIcon(":/res/mhgjsrru.ico"),"load layers");
    connect(m_menu_action, SIGNAL(triggered()), this, SLOT(menu_button_action()));
}

void HelloWorldPlugin::menu_button_action() {
    QgsMessageLog::logMessage(QString("Menu clicked!"), QString("Hello World Plugin"), Qgis::MessageLevel::Info);

    auto treeView = m_qgis_if->layerTreeView();
    if(treeView == nullptr)
    {
        QgsMessageLog::logMessage(QString("tree view is null!"), QString("Hello World Plugin"), Qgis::MessageLevel::Info);
        return;
    }
    auto rootGroup = treeView->layerTreeModel()->rootGroup();

    // 打开文件对话框，让用户选择一个文件
    QString fileName = QFileDialog::getOpenFileName(nullptr,
                                                    "选择文件",
                                                    "",
                                                    "All Files (*)");

    if (fileName.isEmpty())
    {
        QgsMessageLog::logMessage(QString("getOpenFileName canceled!"), QString("Hello World Plugin"), Qgis::MessageLevel::Info);
        return;
    }    

    QString filePath = fileName;
    QFile file(filePath);
    QFileInfo fileInfo(file);

    m_qgis_if->addVectorLayer(filePath,fileInfo.baseName(),"ogr");
}
